package org.example.controller;


import org.example.exception.AppException;
import org.example.model.Setting;
import org.example.model.User;
import org.example.service.SettingService;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private SettingService settingService;

    //这里是处理头像的存储路径
    @Value("${user.head.local-path}")
    private String localPath;

    @PostMapping("/login")
    public Object login(@RequestBody User user,
                        HttpServletRequest req){
        User param = new User();
        param.setUsername(user.getUsername());
        //然后根据账号去查询
        User query = userService.queryByCondition(param);
        if(query == null){
            throw new AppException("USR001","账号不存在");
        }
        if(!query.getPassword().equals(user.getPassword())){
            throw new AppException("USR002","密码不存在或者密码错误");
        }
        //后边很多的新增接口都需要保存我们的setting_id字段，所以提前咋子sessionID中提前保存

        Setting setting = settingService.queryByUserID(query.getId());
        query.setSettingId(setting.getId());

        //走到这里就是验证通过，然后创建session，保存用户信心
        HttpSession session = req.getSession();
        session.setAttribute("user",query);
        return null;
    }

    @PostMapping("/register")
    @Transactional//加入事务
    public Object register(User user, MultipartFile headFile){
        //用户注册：把用户信息插入到数据库用户表（head字段是需要保存图片上传后才有）
        //先保存上传头像文件,路径是本地硬盘路径前缀+路径后缀（随机的）
        try {
            if(headFile != null) {
                String filePath = localPath
                        + File.separator//根据操作系统不同生成分隔符
                        + UUID.randomUUID().toString()
                        + "-"
                        + headFile.getOriginalFilename();//后面这是生成一个随机的字符串+文件本身的名称
                user.setHead(filePath.substring(localPath.length()));
                headFile.transferTo(new File(filePath));
            }
            //注册先插入我们用户表，然后还需要插入设置表，因为用户和抽奖设置一对一，并且抽奖设置页面需要获取这些信息
            int n = userService.insert(user);
            Setting setting = new Setting();
            setting.setUserId(user.getId());
            setting.setBatchNumber(8);//默认的每次抽奖数量
            int m = settingService.insert(setting);
            return null;
        } catch (IOException e) {
            throw new AppException("USR003","上传图片出错",e);
        }
    }

    @GetMapping("/logout")
    public Object logout(HttpSession session){
        session.invalidate();//session失效
        return null;
    }
}
